package com.example.mykotilin.paging2

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asFlow
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import com.example.mykotilin.paging2.repository.RedditPostRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flatMapLatest

class SubRedditViewModel(
    private val repository: RedditPostRepository,
    private val saveStateHandle: SavedStateHandle
) : ViewModel() {
    companion object {
        const val KEY_SUBREDDIT = "subreddit"
        const val DEFAULT_SUBREDDIT = "androiddev"
    }

    init {
        if (!saveStateHandle.contains(KEY_SUBREDDIT)) {
            saveStateHandle.set(KEY_SUBREDDIT, DEFAULT_SUBREDDIT)
        }
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    val posts = saveStateHandle.getLiveData<String>(KEY_SUBREDDIT)
        .asFlow()
        .flatMapLatest {
            repository.postOfSubreddit(it, 30)
        }.cachedIn(viewModelScope)

    //显示
    fun showSubreddit(subreddit: String) {
        if (!shouldShowSubreddit(subreddit)) return
        saveStateHandle.set(KEY_SUBREDDIT, subreddit)
    }

    private fun shouldShowSubreddit(subreddit: String): Boolean {
        return saveStateHandle.get<String>(KEY_SUBREDDIT) != subreddit
    }
}